using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using Avalonia.Controls;
using CommunityToolkit.Mvvm.Input;
using CommunityToolkit.Mvvm.Messaging;
using DialogHostAvalonia;
using Microsoft.Extensions.Logging;
using SchoolApp_Material.Models;
using SchoolApp_Material.Msgs;

namespace SchoolApp_Material.ViewModels;

public class FormEditViewModel : ViewModelBase, INotifyDataErrorInfo
{
    private ILogger<FormEditViewModel> _logger;
    private IFreeSql _freeSql;
    private FormViewModel _form;

    public FormEditViewModel()
    {
        if (!Design.IsDesignMode) return;
    }

    public FormEditViewModel(ILogger<FormEditViewModel> logger, IFreeSql freeSql)
    {
        if (Design.IsDesignMode) return;
        _logger = logger;
        _freeSql = freeSql;
    }

    #region 属性

    private string _year;

    public string Year
    {
        get => _year;
        set
        {
            SetProperty(ref _year, value);
            ValidateYear();
        }
    }


    private string _code;

    public string Code
    {
        get => _code;
        set
        {
            SetProperty(ref _code, value);
            ValidateCode();
        }
    }

    #endregion

    #region 命令

    #region 提交

    private RelayCommand _confirmCmd;

    public RelayCommand ConfirmCmd =>
        _confirmCmd ??= new RelayCommand(ExecuteConfirmCmd, CanExecuteConfirmCmd);

    private void ExecuteConfirmCmd()
    {
        ValidateYear();
        ValidateCode();
        if (HasErrors)
        {
            return;
        }

        int year = int.Parse(Year);

        if (_form.Id == 0)
        {
            if (_freeSql.Select<Form>().Where(f => !f.IsDeleted && f.Year == year && f.Code == Code).Count() > 0)
            {
                WeakReferenceMessenger.Default.Send(new ErrorMsg { Data = $"数据重复：[{year}级-{Code}]的记录已存在" });
                return;
            }

            var rowCount = _freeSql.Insert<Form>(new Form
            {
                Year = int.Parse(Year),
                Code = Code,
                CreateOperatorCode = Common.LoginOperator.Code,
                CreateOperatorName = Common.LoginOperator.Name,
                CreateTime = DateTime.Now
            }).ExecuteAffrows();
            _logger.LogInformation($"新增Form数据{rowCount}行");
        }
        else
        {
            if (_freeSql.Select<Form>().Where(f => !f.IsDeleted && f.Id != _form.Id && f.Year == year && f.Code == Code)
                    .Count() > 0)
            {
                WeakReferenceMessenger.Default.Send(new ErrorMsg { Data = $"数据重复：[{year}级-{Code}]的记录已存在" });
                return;
            }

            var rowCount = _freeSql.Update<Form>()
                .Set(f => f.Year, year)
                .Set(f => f.Code, Code)
                .Set(f => f.UpdateTime, DateTime.Now)
                .Set(f => f.UpdateOperatorCode, Common.LoginOperator.Code)
                .Set(f => f.UpdateOperatorName, Common.LoginOperator.Name)
                .Where(f => f.Id == _form.Id).ExecuteAffrows();
            _logger.LogInformation($"更新Form数据{rowCount}行");
        }

        DialogHost.GetDialogSession(null)?.Close(true);
    }

    private bool CanExecuteConfirmCmd()
    {
        return true;
    }

    #endregion

    #region 取消

    private RelayCommand _cancelCmd;

    public RelayCommand CancelCmd =>
        _cancelCmd ??= new RelayCommand(ExecuteCancelCmd);

    private void ExecuteCancelCmd()
    {
        DialogHost.GetDialogSession(null)?.Close(false);
    }

    #endregion

    #endregion

    #region 方法

    public void InitData(FormViewModel form)
    {
        _form = form;
        Year = _form.Year;
        Code = _form.Code;
    }

    private void ValidateYear()
    {
        _errors.Remove(nameof(Year));
        var errors = new List<string>();

        if (string.IsNullOrWhiteSpace(Year))
        {
            errors.Add("年级不能为空");
        }
        else if (!int.TryParse(Year, out var year))
        {
            errors.Add("年级必须为数字");
        }

        if (errors.Any())
            _errors.Add(nameof(Year), errors);

        ErrorsChanged?.Invoke(this, new DataErrorsChangedEventArgs(nameof(Year)));
    }

    private void ValidateCode()
    {
        _errors.Remove(nameof(Code));
        var errors = new List<string>();

        if (string.IsNullOrWhiteSpace(Code))
            errors.Add("班级不能为空");

        if (errors.Any())
            _errors.Add(nameof(Code), errors);

        ErrorsChanged?.Invoke(this, new DataErrorsChangedEventArgs(nameof(Code)));
    }

    #endregion

    #region INotifyDataErrorInfo 实现

    private readonly Dictionary<string, List<string>> _errors = new();

    public event EventHandler<DataErrorsChangedEventArgs>? ErrorsChanged;
    public bool HasErrors => _errors.Any();

    public IEnumerable GetErrors(string? propertyName) =>
        propertyName != null && _errors.TryGetValue(propertyName, out var errors)
            ? errors
            : Enumerable.Empty<string>();

    #endregion
}